//
//  DataBaseHandle.m
//  Journey
//
//  Created by dllo on 16/5/28.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "DataBaseHandle.h"

@interface DataBaseHandle ()

@property(nonatomic,strong)FMDatabase *myFMDB;
@end


@implementation DataBaseHandle

//单例
+(DataBaseHandle *)shareDataBaseHandle
{
    static DataBaseHandle *dataBase = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dataBase = [[DataBaseHandle alloc] init];
     
    });
    return dataBase;
}

//static sqlite3 *db = nil;
//打开数据库
-(void)zhuanTOpenDB{
    
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject ;
    NSLog(@"%@",path);
    NSString *dataPath = [path stringByAppendingPathComponent:@"dataBase.sqlite"];
    self.myFMDB = [[FMDatabase alloc] initWithPath:dataPath];
    self.myFMDB = [FMDatabase databaseWithPath:dataPath];
    [self.myFMDB open];
    BOOL result = [self.myFMDB open];
    if (result) {
        NSLog(@"数据库打开成功");
    } else {
        NSLog(@"数据库打开失败");
    }
}

//创建表
-(void)ZhuanTCreatTable
{
    BOOL result = [self.myFMDB executeUpdate:@"create table if not exists zhuanT(id integer primary key autoincrement,title text,url text,userName text)"];
    if (result) {
        NSLog(@"表创建成功");
    }else{
    NSLog(@"表创建失败");
    }
}

//插入热门城市数据
-(void)insertZhuanT:(ZhuanTModel *)zhuanT withUserName:(NSString *)userName{
    NSString *sql = [NSString stringWithFormat:@"insert into zhuanT(title,url,userName) values('%@','%@','%@')",zhuanT.title,zhuanT.url,userName];
    
    BOOL result = [self.myFMDB executeUpdate:sql];
    
    if (result) {
        NSLog(@"插入热门城市成功");
    }else{
        NSLog(@"插入热门城市失败");
    }
}



//删除数据
-(void)ZhuanTDeleteTable:(NSString *)title{
    NSString *sql = [NSString stringWithFormat:@"delete from zhuanT where title = '%@'",title];
    BOOL result = [self.myFMDB executeUpdate:sql];
    if (result) {
        NSLog(@"删除成功");
    }else{
        NSLog(@"删除失败");
    }
}

//条件查询
-(NSMutableArray *)selectZhuanT:(NSString *)userName withCompare:(BOOL)compare{
    NSString *sql = [NSString stringWithFormat:@"select * from zhuanT where userName = '%@'",userName];
    FMResultSet *result = [self.myFMDB executeQuery:sql];
    NSMutableArray *array = [NSMutableArray array];
    NSMutableArray *titleArray = [NSMutableArray array];
    if (result) {
        NSLog(@"准备成功");
        
        while ([result next]) {
            ZhuanTModel *model = [[ZhuanTModel alloc] init];
            model.title = [result objectForColumnName:@"title"];
            model.url = [result objectForColumnName:@"url"];
            [array addObject:model];
            [titleArray addObject:model.title];
            
        }
        
    } else {
        NSLog(@"准备失败");
    }
    
    if (compare == YES) {
        return array;
    }else{
        return titleArray;
    }
    
}


@end
